<template>
  <div class="app-container">
    <!--多选框-->
    <el-form
      label-position="left"
      label-width="120px"
      :rules="rules"
      style="padding:0px 0px 0px 0px"
    >
      <el-row :gutter="68">
        <el-col :xs="24" :sm="24" :md="16" :lg="16">
          <el-form-item label="解析无交期物料" >
            <el-button type="primary" @click="parseMaterialVo2Material()">解析</el-button>
          </el-form-item>
          <!--          <el-form-item label="全局搜索">-->
          <!--            <el-col :xs="24" :sm="24" :md="8" :lg="8" style="padding-right:8px!important;padding-left:0!important">-->
          <!--              <el-input id="A_screen" v-model="A_filterContent" ></el-input>-->
          <!--            </el-col>-->
          <!--            <el-button type="primary" @click="searchAll()">搜索</el-button>-->
          <!--          </el-form-item>-->
        </el-col>
      </el-row>
    </el-form>
    <!--   筛选 -->

    <span> &#12288 </span>
    <el-table
      v-loading = "listLoading"
      :data="list.slice((currentPage-1)*pagesize,currentPage*pagesize)"
      element-loading-text="Loading"
      border
      fit
      max-height="580"
      highlight-current-row
      :default-sort="{prop:'date',order:'scending'}"
      :row-class-name="tableRowClassName"
    >



      <el-table-column align="center" label="物料编号" width="120">
        <template slot-scope="techlist">
          <span>{{techlist.row.materialNo}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="物料名称"  prop="date" width="95">
        <template slot-scope="techlist">
          <span>{{techlist.row.materialName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="BOM数量" width="95" prop="date">
        <template slot-scope="techlist">
          <span>{{techlist.row.planQuantity}}</span>
        </template>
      </el-table-column>
      <el-table-column label="机台号"  align="center" prop="address">
        <template slot-scope="techlist">
          <span>{{techlist.row.ACode}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="图号" >
        <template slot-scope="techlist">
          <span>{{techlist.row.figureNo}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="规格" >
        <template slot-scope="techlist">
          <span>{{techlist.row.specs}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="品牌" >
        <template slot-scope="techlist">
          <span>{{techlist.row.brand}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="审批编号" width="150">
        <template slot-scope="techlist">
          <span>{{techlist.row.approvalCode}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="BOM备注" >
        <template slot-scope="techlist">
          <span>{{techlist.row.bomRemark}}</span>
        </template>
      </el-table-column>

    </el-table>

    <el-pagination
      align = "center"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :page-size="pagesize"
      layout="total, prev, pager, next"
      :total="list.length">
    </el-pagination>

  </div>
</template>


<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label{
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
}

</style>


<script>
import { getList } from '@/api/table'
import axios from 'axios';
import Qs from 'qs' //引入json
export default {

  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {

      //用于筛选的数据
      filterContent: '',
      A_filterContent:'',
      //分页数据
      currentPage:1, //初始页
      pagesize:20,    //每页的数据
      rules: {},
      //本次购买:
      //退货数量
      //多选框
      list: [],
      changedList:[], //经过变动的list
      buylist:[],//{购买的material号,机台号，时间，个数，购买还是退货}
      listCopy:[],
      listLoading: false,
    }
  },
  created() {
    this.fetchData()
  },
  methods: {

    useInventory(row){
      this.$confirm('确认使用库存？').then( _ => {
        axios.get("/material/useInventory",{
          params:{
            id: row.id,
          },
        }).then( res => {
          if(res.data.code == "20000"){
            let arr = [...JSON.parse(res.data.data)];
            console.log(arr);
            this.list = arr;
          }
          this.listLoading = false;
        }).catch( res => {
            this.listLoading = false;
          }
        )
      }).catch( _ =>{

      })
    },
    //生成唯一15位字符
    getUUIDAndStorage(){
      let num =this.randomWord(false,30);
    },
    randomWord(randomFlag, min, max){
      var str = "",
        range = min,
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

      // 随机产生
      if(randomFlag){
        range = Math.round(Math.random() * (max-min)) + min;
      }
      for(var i=0; i<range; i++){
        pos = Math.round(Math.random() * (arr.length-1));
        str += arr[pos];
      }
      return str;
    },
    //页面高亮的处理,传进来row和index
    tableRowClassName({row, rowIndex}) {
      if (row.isUrgent === "1") {  //如果是加急的话就这样
        return 'warning-row';
      }
      if(row.unpurchased === "0"){
        return 'success-row';
      }
      return '';
    },
    //分页
    handleSizeChange: function (size) {
      this.pagesize = size;
      console.log(this.pagesize)  //每页下拉显示数据
    },
    handleCurrentChange: function(currentPage){
      this.currentPage = currentPage;
      console.log(this.currentPage)  //点击第几页
    },
    parseMaterialVo2Material(){
      this.listLoading = true;
      axios.get("/materialvo/parseMaterialVo",{
      }).then( res => {
        if(res.data.code == "20000"){
          debugger
          let arr = [...JSON.parse(res.data.data)];
          console.log(arr);
          this.list = arr;
          this.$alert("所有文件解析完成");
        }
        this.listLoading = false;
      }).catch( res => {
          this.listLoading = false;
        }
      )
    },
    Acode_filterhandler(){
      this.listLoading = true;
      axios.get("/excel/Acodefilter",{
        params:{
          content: this.A_filterContent
        },
      }).then( res => {
        if(res.data.code == "20000"){
          let arr = [...JSON.parse(res.data.data)];
          console.log(arr);
          this.list = arr;
        }
        this.listLoading = false;
      }).catch( res => {
          this.listLoading = false;
        }
      )
    },
    // searchAll(){
    //
    // }
    // ,
    //输入本次购买之后 需购加上 已购减去
    clickbuy(row){

    },
    //点击退货之后 处理退货的内容
    backgoodsSolve(row){
      if(row.backGoods){
        //退货后
        // row.purchased =  String(parseInt(row.purchased) - parseInt(row.backGoods));
        // row.unpurchased = String(parseInt(row.unpurchased) + parseInt(row.backGoods));
        // row.quantity = String( parseInt(row.quantity) - parseInt(row.backGoods));
        // this.changedList.push(row)
        // row.backGoods = '';
      }
    },
    clearCart(){
      this.listLoading = true;
      axios.get('/excel/clearCart',{
        params:{
          userName: localStorage.getItem("userName")
        },
      }).then( res =>{
        if(res.data.code == "20000"){
          let arr = [...JSON.parse(res.data.data)];
          console.log(arr);
          this.list = arr;
        }
        this.listLoading = false;
      }).catch( res => {
        this.listLoading = false;
      })
    },
    buyCart(){
      this.listLoading = true;
      axios.get("/cart-goods/getMyCart",{
        params:{
          userName: localStorage.getItem("userName")
        },
      }).then( res => {
        if(res.data.code == "20000"){
          let arr = [...JSON.parse(res.data.data)];
          console.log(arr);
          this.list = arr;
        }else {
          this.$alert("请登陆后使用");
        }
        this.listLoading = false;
      }).catch( res => {
          this.listLoading = false;
        }
      )
    },
    //获得已完成的，即需购小于0
    getHaveFinished(){
      this.listLoading = true;

      axios.get("/excel/getHaveFinishedBuy",{
        params:{
          content: this.filterContent
        },
      }).then( res => {
        if(res.data.code == "20000"){
          let arr = [...JSON.parse(res.data.data)];
          console.log(arr);
          this.list = arr;
          this.showInventory = true;
        }
        this.listLoading = false;
      }).catch( res => {
          this.listLoading = false;
        }
      )
    },
    //获得需购为0的
    getNeedBuyZero(){
      this.listLoading = true;
      axios.get("/excel/allPruchased",{
        params:{
          content: this.filterContent
        },
      }).then( res => {
        if(res.data.code == "20000"){
          let arr = [...JSON.parse(res.data.data)];
          console.log(arr);
          this.list = arr;
        }
        this.listLoading = false;
      }).catch( res => {
          this.listLoading = false;
        }
      )
    },
    filterUrgent(){
      this.listLoading = true;
      axios.get("/excel/urgentfilter",{
        params:{
          content: this.filterContent
        },
      }).then( res => {
        if(res.data.code == "20000"){
          let arr = [...JSON.parse(res.data.data)];
          console.log(arr);
          this.list = arr;
        }
        this.listLoading = false;
      }).catch( res => {
          this.listLoading = false;
        }
      )
    },
    //填充本次购买
    fillThisPurchase(){
      for(var row = 0; row < this.list.length ;row++){
        this.list[row].thisPurchase = this.list[row].unpurchased;
        this.$set(this.list,row,this.list[row]);//更新此行数据
      }
    },
    clearAllThisPurchase(){
      for(var row = 0; row < this.list.length ;row++){
        this.list[row].thisPurchase = '';
        this.$set(this.list,row,this.list[row]);//更新此行数据
      }
    },
    //经过本次购买和退货数量，最终的结果推回后端
    pushPurchase_back2Sever(){
      this.changedList = [];
      this.listLoading = true;
      for(var row = 0; row < this.list.length ;row++){
        if(this.list[row].thisPurchase){
          this.list[row].purchased =  String(parseInt(this.list[row].thisPurchase) + parseInt(this.list[row].purchased));
          this.list[row].unpurchased = String(parseInt(this.list[row].unpurchased) - parseInt(this.list[row].thisPurchase));
          this.changedList.push(this.list[row])
          this.buylist.push(
            {
              "id":this.list[row].id,
              "materialNo": this.list[row].materialNo,
              "equipmentNo":this.list[row].equipmentNo,
              "time":this.list[row].delivery,
              "buy_num":this.list[row].thisPurchase,
              "back_num":"0"
            })
        }
        if(this.list[row].backGoods){
          this.list[row].purchased =  String(parseInt(this.list[row].purchased) - parseInt(this.list[row].backGoods));
          this.list[row].unpurchased = String(parseInt(this.list[row].unpurchased) + parseInt(this.list[row].backGoods));
          this.changedList.push(this.list[row])
          this.buylist.push(
            {
              "id":this.list[row].id,
              "materialNo": this.list[row].materialNo,
              "equipmentNo":this.list[row].equipmentNo,
              "time":this.list[row].delivery,
              "buy_num":"0",
              "back_num":this.list[row].backGoods
            })
          // row.quantity = String( parseInt(row.quantity) - parseInt(row.backGoods));   等待上传Bom表平内容
        }
      }
      let data = {"buyarray":this.changedList,"userName":localStorage.getItem("userName"),"buyArrSimple":this.buylist};
      axios.post('/cart-goods/buyMaterial',data)
        .then( res => {
          if(res.data.code == "20000"){
            for(var i=0; i < this.list.length; i++){
              this.list[i].thisPurchase = '';
              this.list[i].backGoods = '';
            }
            for(var j = 0; j < this.list.length;j++){
              this.list[j].thisPurchase = '';
              this.list[j].backGoods = '';
            }
            this.$alert("更新成功");
            this.buylist=[];
          }else if(res.data.code == "40000"){
            this.$alert(res.data.data);
          }
          this.listLoading = false;
        }).catch( f=>{
        this.listLoading = false;
      } )
    },
    //列表内的值重置到全部的值(重置按钮)
    reset2AllData(){
      this.listLoading = true;
      axios.get("/excel/reset",{
        params:{
          content: this.filterContent
        },
      }).then( res => {
        if(res.data.code == "20000"){
          let arr = [...JSON.parse(res.data.data)];
          console.log(arr);
          this.list = arr;

        }
        this.listLoading = false;
      }).catch( res => {
          this.listLoading = false;
        }
      )
    },
    //导出excel
    export2buy(){
      axios.get('/cart-goods/getPurchaseExcel',{
        responseType: 'blob',
        params:{
          userName:localStorage.getItem("userName"),
        }
      }).then((response) =>{
        //新更新表格数据
        this.list = Object.assign([],this.list);

        let blob = new Blob([response.data],{type:'application/octet-stream'});
        let link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = "采购.xls";
        link.click();
        // this.list = [];
        this.$alert("导出成功");
      }).catch( f=>{
        }
      );
    },
    openM() {
      this.$alert("导出成功");
    },

    fetchData() {
      this.listLoading = true;

      axios.get('/materialvo/getMaterialVo').then( (res) => {
        if (res.data.code == "20000"){
          let arr = [...JSON.parse(res.data.data)];
          this.list = arr;
          this.listCopy = this.list;
        }
        this.listLoading = false;
      }).catch(f =>{
        this.listLoading = false;
      })
    }
  }
}
</script>
